package com.wuzhazha.javamind.chapter15.test04;

import java.util.Iterator;
import java.util.Random;

/**
 * 作用：为了随机生成不同类型的Coffee对象。为了可以使用foreach的循环功能，必须实现迭代器接口Iterable，
 */
public class CoffeeGenerator implements Generator<Coffee>,Iterable<Coffee> {

    private Class[] types = new Class[]{Latte.class,Mocha.class,Cappuccino.class,Americano.class,Breve.class};

    private static Random rand = new Random(47);

    public CoffeeGenerator(){}

    private int size = 0;

    public CoffeeGenerator(int size){
        this.size = size;
    }

    /**
     * 随机生成一个Coffee的实例
     * @return
     */
    public Coffee next() {
        try {
        return (Coffee) types[rand.nextInt(types.length)].newInstance();
        } catch (Exception e) {
            throw new RuntimeException();
        }
    }

    /**
     * 实现了该方法，就具有循环迭代功能
     * @return
     */
    public Iterator<Coffee> iterator() {
        return new Iterator<Coffee>() {

            int count = size;

            public boolean hasNext() {
                return count > 0;//末端哨兵，判断何时停止
            }

            /**
             * 每次取出时候总数减1
             * @return
             */
            public Coffee next() {
                count--;
                return CoffeeGenerator.this.next();
            }

            public void remove() {
                throw new UnsupportedOperationException();
            }
        };
    }

    public static void main(String[] args) {
        CoffeeGenerator gen = new CoffeeGenerator();
        for(int i = 0 ; i < 5; i++){
            System.out.println(gen.next());
        }
        for (Coffee coffee : new CoffeeGenerator(5)) {
            System.out.println(coffee);
        }
    }
}
